package cmd

import (
	"fmt"
	"im-tools/internal/config"
	"im-tools/internal/model"
	"im-tools/internal/service"
	"time"

	"log"
	"net/http"

	"github.com/duke-git/lancet/netutil"
	"github.com/goccy/go-json"
	"github.com/gookit/color"
	"github.com/spf13/cobra"
	"golang.org/x/exp/rand"
)

var createCmd = &cobra.Command{
	Use:   "createGroup",
	Short: "建群",
	Long:  `批量建群`,
	Run: func(cmd *cobra.Command, args []string) {
		var groupCount int  //群数量
		var memberCount int //每个群的人数
		for {
			color.Info.Println("输入批量建群的数量")
			if _, err := fmt.Scanln(&groupCount); err != nil {
				continue
			}

			color.Info.Println("输入群成员人数:")
			if _, err := fmt.Scanln(&memberCount); err != nil {
				continue
			}

			if groupCount > 0 && memberCount > 0 {
				break
			} else {
				color.Warn.Println("输入有误,请重新输入!")
			}
		}

		if Token == "" {
			log.Printf("%v \n", "Token不能为空,请先登录获取有效token")
			return
		}

		log.Printf("开始批量创建 %d 个群\n", groupCount)

		for i := 0; i < groupCount; i++ {
			createGroup(memberCount)
			time.Sleep(1 * time.Second)
		}
	},
}

func createGroup(memberCount int) {
	request := &netutil.HttpRequest{
		RawURL: config.API + "/api/zkim/group/createGroup",
		Method: "POST",
	}

	headers := http.Header{}
	headers.Add("Content-Type", "application/json")
	headers.Add("satoken", Token)
	request.Headers = headers

	us := service.UserService{}

	userIds := []model.GroupMember{}

	users := us.SelectUsers(memberCount)
	// shuffledArr := shuffleArray(users)
	for _, u := range users {
		if u.FakeUid == LoginedUserId {
			continue
		}
		userIds = append(userIds, model.GroupMember{
			UserId:   u.FakeUid,
			Nickname: u.Nickname,
		})
		color.Info.Printf("添加成员: %s [%s]\n", u.FakeUid, u.Nickname)
	}

	createGroupReq := &model.CreateGroup{
		Members: userIds,
	}

	postData, err := json.Marshal(createGroupReq)
	if err != nil {
		color.Error.Println(err)
		return
	}
	request.Body = postData
	httpClient := netutil.NewHttpClient()
	resp, err := httpClient.SendRequest(request)
	if err != nil || resp.StatusCode != 200 {
		color.Error.Println(resp.StatusCode)
		return
	}
	color.Info.Printf("建群结束 %v\n", resp.StatusCode)
}

// 通过生成随机索引并交换数组元素来打乱顺序
func shuffleArray(arr []model.UserModel) []model.UserModel {
	// 使用当前时间戳作为随机数生成器的种子，确保每次运行结果不同
	rand.Seed(uint64(time.Now().UnixNano()))
	for i := len(arr) - 1; i > 0; i-- {
		// 生成一个范围在0到i之间（包含0和i）的随机索引
		j := rand.Intn(i + 1)
		// 交换arr[i]和arr[j]的位置
		arr[i], arr[j] = arr[j], arr[i]
	}
	return arr
}
func init() {
	// createCmd.Flags().Int32P("count", "c", 0, "输入批量建群的数量")
	rootCmd.AddCommand(createCmd)
}
